<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <!--
      <el-form-item label="租户ID" prop="tenantId">
          <el-input
          v-model="queryParams.tenantId"
          placeholder="请输入租户ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item> 
      -->
      <el-form-item label="房屋地址" prop="homeownersContractId">
        <el-input
          v-model="queryParams.addressSearchKey"
          placeholder="请输入"
          clearable
        />
      </el-form-item>
      <el-form-item label="租客姓名" prop="tenantName">
        <el-input
          v-model="queryParams.tenantName"
          placeholder="请输入"
          clearable
        />
      </el-form-item>
      <el-form-item label="合同状态" prop="contractStatus">
        <el-select
          v-model="queryParams.contractStatus"
          placeholder="请选择"
          clearable
          class="w-160px"
        >
          <el-option
            v-for="item in contractStatusOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="合同开始时间" prop="contractStartTime">
        <el-date-picker clearable
          v-model="queryParams.contractStartTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择合同开始时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="合同结束时间" prop="contractEndTime">
        <el-date-picker clearable
          v-model="queryParams.contractEndTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择合同结束时间">
        </el-date-picker>
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['fang:leasecontract:add']"
          >新增</el-button
        >
      </el-form-item>
    </el-form>

    <!-- <el-row :gutter="10" class="mb8">
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row> -->
    
    <!-- 标签页和新增按钮 -->
    <div class="tabs-with-button mb-4">
      <el-tabs v-model="tabVal" @tab-change="handleTabChange" v-hasPermi="['fang:leasecontract:add']">
        <el-tab-pane label="已完成信息合同" name="1"></el-tab-pane>
        <el-tab-pane name="2">
          <template #label>
            <el-badge :value="unfinishedCount" v-if="unfinishedCount > 0">
              <span>未完成信息合同</span>
            </el-badge>
            <span v-else>未完成信息合同</span>
          </template>
        </el-tab-pane>
      </el-tabs>
      <div class="tabs-button-wrapper">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['fang:leasecontract:add']"
          >新增</el-button
        >
      </div>
    </div>

    <el-table
      v-loading="loading"
      :data="leasecontractList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="自增ID" align="center" prop="id" /> -->
      <el-table-column label="租户名称" align="center" prop="tenantName" />
      <el-table-column label="联系电话" align="center" prop="phone" />
      <el-table-column
        label="起始日期"
        align="center"
        prop="contractStartTime"
        width="180"
      >
        <template #default="scope">
          <span>{{
            parseTime(scope.row.contractStartTime, "{y}-{m}-{d}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="到期日期"
        align="center"
        prop="contractEndTime"
        width="180"
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.contractEndTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="合同状态"
        align="center"
        prop="contractStatus"
        :formatter="contractStatusText"
      />

      <!-- <el-table-column label="租户ID" align="center" prop="tenantId" /> -->
      <!-- <el-table-column label="托管房源" align="center" prop="homeownersContractId" /> -->

      <!-- <el-table-column label="说明" align="center" prop="contractDescribe" />
       -->

      <!-- <el-table-column label="身份证文件" align="center" prop="identityFile" />
      <el-table-column label="身份证文件url" align="center" prop="identityFileUrl" />
      <el-table-column label="管理费文件" align="center" prop="tenantManagementFeeFile" />
      <el-table-column label="管理费文件url" align="center" prop="tenantManagementFeeFileUrl" />
      <el-table-column label="租房合同文件" align="center" prop="tenantContractFile" />
      <el-table-column label="租房合同文件url" align="center" prop="tenantContractFileUrl" />
      <el-table-column label="交接文件" align="center" prop="tenantHandoverFile" />
      <el-table-column label="交接文件url" align="center" prop="tenantHandoverFileUrl" /> -->
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['fang:leasecontract:query']"
            >合同详情</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </div>
</template>

<script setup name="Leasecontract">
import {
  listLeasecontract,
  delLeasecontract,
  getUnfinishedCount,
} from "@/api/fang/leasecontract";
import {
  LEASE_CONTRACT_STATUS,
  LEASE_CONTRACT_STATUS_TEXT,
} from "@/utils/enums";

import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { download as downloadFile } from '@/utils/request'

const router = useRouter()
const queryRef = ref()
const tabVal = ref("1");

const leasecontractList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const unfinishedCount = ref(0);

const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    tenantId: null,
    homeownersContractId: null,
    tenantName: null,
    phone: null,
    contractDescribe: null,
    contractStatus: null,
    contractStartTime: null,
    contractEndTime: null,
    identityFile: null,
    identityFileUrl: null,
    tenantManagementFeeFile: null,
    tenantManagementFeeFileUrl: null,
    tenantContractFile: null,
    tenantContractFileUrl: null,
    tenantHandoverFile: null,
    tenantHandoverFileUrl: null,
  },
  rules: {},
});

const { queryParams } = toRefs(data);

// 标签页切换处理
function handleTabChange(tabName) {
  // tab切换时重置页数为1并重新获取列表
  queryParams.value.pageNum = 1;
  getList();
}

// 监听tab切换（保留兼容性）
watch(tabVal, (newVal, oldVal) => {
  if (newVal !== oldVal) {
    // tab切换时重置页数为1并重新获取列表
    queryParams.value.pageNum = 1;
    getList();
  }
});

// 合同状态选项
const contractStatusOptions = [
  {
    value: LEASE_CONTRACT_STATUS.DRAFT,
    label: LEASE_CONTRACT_STATUS_TEXT[LEASE_CONTRACT_STATUS.DRAFT],
  },
  {
    value: LEASE_CONTRACT_STATUS.VALID,
    label: LEASE_CONTRACT_STATUS_TEXT[LEASE_CONTRACT_STATUS.VALID],
  },
  {
    value: LEASE_CONTRACT_STATUS.INVALID,
    label: LEASE_CONTRACT_STATUS_TEXT[LEASE_CONTRACT_STATUS.INVALID],
  },
];

function contractStatusText(row, column, cellValue) {
  return LEASE_CONTRACT_STATUS_TEXT[cellValue] || "未知状态";
}

/** 查询租赁合同列表 */
function getList() {
  loading.value = true;
  const params = {
    ...queryParams.value,
  };
  
  if (tabVal.value == "1") {
    // 已完成列表：搜索按具体值搜索，如果下拉框没有值默认传入-1，包括合同有效和无效
    if (params.contractStatus === null || params.contractStatus === undefined || params.contractStatus === '') {
      params.contractStatus = -1;
    }
  } else {
    // 未完成列表：传入contractStatus 0，忽略搜索下拉框的值
    params.contractStatus = LEASE_CONTRACT_STATUS.DRAFT;
  }
  
  listLeasecontract(params).then((response) => {
    leasecontractList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

/** 获取未完成合同数量 */
function getUnfinishedContractCount() {
  getUnfinishedCount().then((response) => {
    unfinishedCount.value = response.data || 0;
  }).catch(() => {
    unfinishedCount.value = 0;
  });
}

// 无需维护新增/编辑表单，列表页仅保留检索表单

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  if (queryRef?.value && typeof queryRef.value.resetFields === 'function') {
    queryRef.value.resetFields()
  }
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  // reset()
  // open.value = true
  // title.value = "添加租赁合同"
  router.push({ path: '/fang/leasecontract/create' })
}

/** 修改按钮操作 */
function handleUpdate(row) {
  // reset()
  // const _id = row.id || ids.value
  // getLeasecontract(_id).then(response => {
  //   form.value = response.data
  //   open.value = true
  //   title.value = "修改租赁合同"
  // })

  console.log("修改稿11111111111111");
  const id = row.id;
  router.push({ path: `/fang/leasecontract/${id}` })
}

// 无提交表单逻辑：新增/编辑通过路由跳转到详情页处理

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  ElMessageBox.confirm('是否确认删除租赁合同编号为"' + _ids + '"的数据项？', '提示', { type: 'warning' })
    .then(() => delLeasecontract(_ids))
    .then(() => {
      getList();
      ElMessage.success("删除成功");
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  downloadFile(
    "fang/leasecontract/export",
    {
      ...queryParams.value,
    },
    `leasecontract_${new Date().getTime()}.xlsx`
  );
}

getList();
getUnfinishedContractCount();
</script>

<style scoped>
.tabs-with-button {
  position: relative;
}

.tabs-button-wrapper {
  position: absolute;
  top: 0;
  right: 0;
  z-index: 10;
}
</style>
